import { OrderType } from '@/enums'
import {
  cancelOrder,
  delOrder,
  followOrUnfollow,
  getPrescriptionUrl
} from '@/services/consult'
import { getMedicalOrderDetail } from '@/services/order'
import type { ConsultOrderItem } from '@/types/consult'
import type { OrderDetail } from '@/types/order'
import type { FollowType } from '@/types/user'
import { showFailToast, showImagePreview, showSuccessToast } from 'vant'
import { onMounted } from 'vue'
import { ref } from 'vue'

// 关注逻辑
export const useFollow = (type: FollowType = 'doc') => {
  const loading = ref(false)
  // const follow = async (item: Doctor) => {
  const follow = async (item: { id: string; likeFlag: 0 | 1 }) => {
    // loading状态 - 加载中
    loading.value = true
    try {
      await followOrUnfollow(item.id, type)
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
    } finally {
      // loading状态 - 恢复默认
      loading.value = false
    }
  }
  return {
    loading,
    follow
  }
}

// 处方预览
export const useShowPrescription = () => {
  const showImage = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionUrl(id)
      showImagePreview([res.data.url])
    }
  }
  return { showImage }
}

// 取消订单
export const useCancelOrder = () => {
  const loading = ref(false)
  const onCancelOrder = async (item: ConsultOrderItem) => {
    loading.value = true
    try {
      await cancelOrder(item.id)
      // 更改当前订单的状态
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
      showSuccessToast('订单修改成功')
    } catch (error) {
      showFailToast('订单修改失败')
    } finally {
      loading.value = false
    }
  }
  return { loading, onCancelOrder }
}

// 删除订单
export const useDelOrder = (cb?: () => void) => {
  const deleteLoading = ref(false)
  const onDeleteOrder = async (item: ConsultOrderItem) => {
    deleteLoading.value = true
    try {
      await delOrder(item.id)
      // 根据不同的业务 - 做不同的事
      // 问诊记录 - 派发事件 通知父组件 删除某一项
      // 问诊详情 - 跳转到问诊记录
      cb && cb()
      showSuccessToast('删除成功')
    } catch (error) {
      showFailToast('删除失败')
    } finally {
      deleteLoading.value = false
    }
  }
  return { deleteLoading, onDeleteOrder }
}

// 药品订单详情
export const useMedicalDetail = (id: string) => {
  const order = ref<OrderDetail>()

  onMounted(async () => {
    const res = await getMedicalOrderDetail(id)
    order.value = res.data
  })
  return { order }
}
